#!/bin/sh

if [ -n "$1" ]; then
    data_date=$1
else
  data_date=$(date -d "-1 days" +%F)
fi

LOAD_DATA_TMP_LOG="
insert overwrite table xm1_tmp.tmp_log
select
   account, appid, appversion, carrier, deviceid, devicetype, eventid, ip, latitude, longitude, nettype, osname, osversion,
 properties, releasechannel, resolution, sessionid, timestamp, dt
    from xm1_ods.ods_log
where dt='${data_date}' and
      deviceid is not null and length(deviceid)!=0
and   eventid is not null and length(eventid)!=0
and   sessionid is not null and length(sessionid)!=0
and   properties is not null and size(properties)!=0;"

LOAD_DATA_TMP_NEW_SESSION="
create table if not exists xm1_tmp.tmp_log_new_session
as
select
    account, appid, appversion, carrier, deviceid, devicetype, eventid, ip, latitude,
    longitude, nettype, osname, osversion, properties, releasechannel, resolution, sessionid, timestamp, dt,
    last_value(new_session_id,true) over (partition by sessionid order by timestamp) as new_session_id
from (select
          *,
          if(time_diff/1000/60>10,concat(sessionid,'-',timestamp),null) as new_session_id
      from (select
           *,
                timestamp-last_timestamp as time_diff
            from ( select
                     *,
                       lag(timestamp,1,0) over (partition by sessionid order by timestamp) as last_timestamp
                   from xm1_tmp.tmp_log) t1
            ) t2
      ) t3;"

/opt/module/spark/bin/beeline -u jdbc:hive2://node101:10001 -n bwie -e "${LOAD_DATA_TMP_LOG}${LOAD_DATA_TMP_NEW_SESSION}"